import { ref, reactive, computed } from 'vue'
import type { MovieUploadForm } from './types'

export const useMovieForm = () => {
  // 表单数据
  const form = reactive<MovieUploadForm>({
    title: '',
    originalTitle: '',
    year: new Date().getFullYear(),
    duration: '',
    directors: [] as string[],
    universe: '',
    language: '',
    country: '',
    rating: 0,
    genres: [] as string[],
    tags: [] as string[],
    actors: [] as string[],
    description: '',
    plot: '',
    budget: '',
    box_office: '',
    awards: [] as string[],
    trivia: [] as string[],
    isAi: false
  })

  // 文件上传
  const coverFile = ref<File | null>(null)
  const coverPreview = ref<string>('')
  const originalCoverUrl = ref<string>('')
  const compressedCoverFile = ref<File | null>(null) // 新增：存储压缩后的文件

  // 临时输入
  const newTag = ref('')
  const newDirector = ref('')
  const newActor = ref('')
  const newAward = ref('')
  const newTrivia = ref('')

  // 计算属性
  const isFormValid = computed(() => {
    return (
      form.title.trim() !== '' &&
      form.year > 0 &&
      form.duration.trim() !== '' &&
      form.directors.length > 0 &&
      form.description.trim() !== '' &&
      form.genres.length > 0 &&
      form.actors.length > 0
    )
  })

  // 表单操作方法
  const toggleGenre = (genre: string) => {
    const index = form.genres.indexOf(genre)
    if (index > -1) {
      form.genres.splice(index, 1)
    } else {
      form.genres.push(genre)
    }
  }

  const addTag = () => {
    if (newTag.value.trim() && !form.tags.includes(newTag.value.trim())) {
      form.tags.push(newTag.value.trim())
      newTag.value = ''
    }
  }

  const removeTag = (tag: string) => {
    const index = form.tags.indexOf(tag)
    if (index > -1) {
      form.tags.splice(index, 1)
    }
  }

  const addDirector = () => {
    if (newDirector.value.trim() && !form.directors.includes(newDirector.value.trim())) {
      form.directors.push(newDirector.value.trim())
      newDirector.value = ''
    }
  }

  const removeDirector = (director: string) => {
    const index = form.directors.indexOf(director)
    if (index > -1) {
      form.directors.splice(index, 1)
    }
  }

  const addActor = () => {
    if (newActor.value.trim() && !form.actors.includes(newActor.value.trim())) {
      form.actors.push(newActor.value.trim())
      newActor.value = ''
    }
  }

  const removeActor = (actor: string) => {
    const index = form.actors.indexOf(actor)
    if (index > -1) {
      form.actors.splice(index, 1)
    }
  }

  const addAward = () => {
    if (newAward.value.trim() && !form.awards.includes(newAward.value.trim())) {
      form.awards.push(newAward.value.trim())
      newAward.value = ''
    }
  }

  const removeAward = (award: string) => {
    const index = form.awards.indexOf(award)
    if (index > -1) {
      form.awards.splice(index, 1)
    }
  }

  const addTrivia = () => {
    if (newTrivia.value.trim() && !form.trivia.includes(newTrivia.value.trim())) {
      form.trivia.push(newTrivia.value.trim())
      newTrivia.value = ''
    }
  }

  const removeTrivia = (trivia: string) => {
    const index = form.trivia.indexOf(trivia)
    if (index > -1) {
      form.trivia.splice(index, 1)
    }
  }

  // 文件处理方法
  const setCoverFile = (file: File) => {
    coverFile.value = file
    compressedCoverFile.value = null // 重置压缩文件
    const reader = new FileReader()
    reader.onload = (e) => {
      coverPreview.value = e.target?.result as string
    }
    reader.readAsDataURL(file)
  }

  const removeCoverFile = () => {
    coverFile.value = null
    compressedCoverFile.value = null // 重置压缩文件
    // 如果没有原始封面URL，则清空预览
    if (!originalCoverUrl.value) {
      coverPreview.value = ''
    } else {
      coverPreview.value = originalCoverUrl.value
    }
  }

  const resetCoverFile = () => {
    coverFile.value = null
    compressedCoverFile.value = null // 重置压缩文件
    coverPreview.value = originalCoverUrl.value
  }

  // 设置压缩后的文件（新增方法）
  const setCompressedCoverFile = (file: File) => {
    compressedCoverFile.value = file
  }

  // 重置表单
  const resetForm = () => {
    // 重置表单数据
    Object.assign(form, {
      title: '',
      originalTitle: '',
      year: new Date().getFullYear(),
      duration: '',
      directors: [],
      universe: '',
      language: '',
      country: '',
      rating: 0,
      genres: [],
      tags: [],
      actors: [],
      description: '',
      plot: '',
      budget: '',
      box_office: '',
      awards: [],
      trivia: [],
      isAi: false
    })

    // 重置文件
    coverFile.value = null
    coverPreview.value = ''
    originalCoverUrl.value = ''
    compressedCoverFile.value = null // 重置压缩文件

    // 重置临时输入
    newTag.value = ''
    newDirector.value = ''
    newActor.value = ''
    newAward.value = ''
    newTrivia.value = ''
  }

  // 设置原始封面URL（用于编辑模式）
  const setOriginalCoverUrl = (url: string) => {
    originalCoverUrl.value = url
    coverPreview.value = url
  }

  // 填充表单数据（用于编辑模式）
  const populateForm = (data: Partial<MovieUploadForm>) => {
    Object.assign(form, data)
  }

  return {
    // 表单数据
    form,
    coverFile,
    coverPreview,
    originalCoverUrl,
    compressedCoverFile, // 新增：暴露压缩文件
    
    // 临时输入
    newTag,
    newDirector,
    newActor,
    newAward,
    newTrivia,
    
    // 计算属性
    isFormValid,
    
    // 方法
    toggleGenre,
    addTag,
    removeTag,
    addDirector,
    removeDirector,
    addActor,
    removeActor,
    addAward,
    removeAward,
    addTrivia,
    removeTrivia,
    setCoverFile,
    removeCoverFile,
    resetCoverFile,
    setCompressedCoverFile, // 新增：暴露设置压缩文件的方法
    setOriginalCoverUrl,
    populateForm,
    resetForm
  }
}
